package com.fanjun.androiddemo.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.fanjun.androiddemo.R;
import com.fanjun.androiddemo.adapter.BookListAdapter;
import com.fanjun.androiddemo.utils.StaticClass;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ListActivity extends AppCompatActivity implements AbsListView.OnScrollListener {

    private SwipeRefreshLayout swipeRefreshLayout;
    private ListView lv;
    private BookListAdapter adapter;
    private View footerView;
    private int visibleLastIndex;//用来可显示的最后一条数据的索引
    private List<Map<String, Object>> images = new ArrayList<>();

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            switch (message.what) {
                case StaticClass.UPDATE_LIST_DATA:
                    if (swipeRefreshLayout.isRefreshing()) {
                        adapter.notifyDataSetChanged();
                        swipeRefreshLayout.setRefreshing(false);//取消刷新的动画
                    }
                    break;
            }
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_container);
        initView();

    }

    private void initView() {
        lv = (ListView) findViewById(R.id.main_lv);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.main_srl);

        footerView = getLayoutInflater().inflate(R.layout.loading_layout, null);
        lv.setOnScrollListener(this);
        String url = StaticClass.DOMAIN + "/book/getList?currentPage=1&limit=10";

        //okhttp 提交数据
        //...
        //...

        //通过handler发送一个更新数据的标记
        handler.sendEmptyMessage(StaticClass.UPDATE_LIST_DATA);

    }

    @Override
    public void onScrollStateChanged(AbsListView absListView, int scrollState) {
        if (adapter.getCount() == visibleLastIndex && scrollState == SCROLL_STATE_IDLE) {
            //new LoadDataThread().start();
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        visibleLastIndex = firstVisibleItem + visibleItemCount - 1;//减去最后一个加载中那条
    }
}
